package com.wswy.wyjk.ui.main.presenter;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.task.DownloadTask;
import com.my.httpapi.api.baseMyView.IosAlertDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wswy.wyjk.ui.dialog.CircleProgressDialog;

public class MainPresenter {
    private AppCompatActivity activity;
    RxPermissions rxPermissions;

    public MainPresenter(AppCompatActivity appCompatActivity) {
        this.activity = appCompatActivity;
        rxPermissions = new RxPermissions(appCompatActivity);
    }

    public void init() {
        isPermission();
    }

    @SuppressLint("CheckResult")
    private void isPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(granted -> {
                        if (granted) {
                            // 获取到权限
                            downLoadDB();
                        }
                    });
            return;
        }
        //api小于23情况
        downLoadDB();
    }

    private void downLoadDB() {
        new IosAlertDialog(activity).builder().setTitle("更新驾考题库").setMsg("有最新都驾考题库")
                .setPositiveButton("更新", v -> {
                    //        String url=  AppContext.getContext().getDatabasePath("wyjk.db").getParent();
//        Aria.download(this)
//                .load("")
//                .setFilePath(url + "/wyjk.db")
//                .create();
                    showProgress();
                }).setNegativeButton("不更新", v -> {
        }).show();
    }


    private void showProgress() {
        CircleProgressDialog.Builder builder = new CircleProgressDialog.Builder(activity);
        builder.create().show();
        float progress = (float) (Math.random() * 100);
        builder.loadProgress(progress);
    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning
    protected void running(DownloadTask task) {
        int p = task.getPercent();    //任务进度百分比
        String speed = task.getConvertSpeed();    //转换单位后的下载速度，单位转换需要在配置文件中打开
        // String speed1 = task.getSpeed(); //原始byte长度速度
    }

    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        //在这里处理任务完成的状态
    }

}
